﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Interfaces.Infrastructure;

namespace Framework.Security
{
    //todo inplement read key from files
    public class RijndaelEncriptionService : IEncriptionService
    {
        static private readonly byte[] InitIv = new byte[] { 0x87, 0xf9, 0xee, 0xc0, 0xe5, 0x67, 0x70, 0x97, 0x40, 0x3e, 0xe4, 0x89, 0xe4, 0x02, 0xb2, 0x88 };
        static private readonly byte[] Key = new byte[] { 0xbd, 0xbd, 0x4c, 0x84, 0x35, 0xfe, 0xad, 0xdb, 0xde, 0x65, 0xc1, 0x06, 0x61, 0x4a, 0x57, 
            0xb3, 0xa5, 0xe7, 0xbd, 0xc4, 0x7d, 0xa0, 0xd2, 0xf7, 0x32, 0xb0, 0x83, 0x56, 0xd5, 0x0e, 0xbf, 0x9b };

        private const int MaxReadedDataLength = 1000;

        public string Encript(string data)
        {
            
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                
                using (var oCrypto = new RijndaelManaged())
                {
                    using (ICryptoTransform oXForm = oCrypto.CreateEncryptor(Key, InitIv))
                    {
                        using (var oMemStream = new MemoryStream())
                        {
                            using (var oCryptStream = new CryptoStream(oMemStream, oXForm, CryptoStreamMode.Write))
                            {
                                oCryptStream.Write(buffer, 0, buffer.Length);
                                oCryptStream.FlushFinalBlock();
                                return Convert.ToBase64String(oMemStream.GetBuffer(), 0, (int)oMemStream.Length);
                            }
                        }
                    }
                }
            
            
        }

        public string Decript(string data)
        {
            byte[] buffer = Convert.FromBase64String(data);
            // Decrypt
            using (var oCrypto = new RijndaelManaged())
            {
                using (ICryptoTransform oXForm = oCrypto.CreateDecryptor(Key, InitIv))
                {
                    using (var oMemStream = new MemoryStream(buffer))
                    {
                        using (var oCryptStream = new CryptoStream(oMemStream, oXForm, CryptoStreamMode.Read))
                        {
                            var abyDecrypted = new byte[MaxReadedDataLength];
                            int iRead = oCryptStream.Read(abyDecrypted, 0, abyDecrypted.Length);
                            // convert to a string
                            string strDecrypted = Encoding.UTF8.GetString(abyDecrypted, 0, iRead);
                            return strDecrypted;
                        }
                    }
                }
            }
        }
    }
}
